<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>

      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
    <!--用户抽屉-->
    <UserDrawer @register="registerDrawer" @success="handleSuccess" />
    <a-modal v-model:visible="visible" @ok="handleOk">
      <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }" style="padding-top: 50px;">
        <a-form-item label="等级">
          <JDictSelectTag dictCode="level" v-model:value="level">
          </JDictSelectTag>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:visible="editUp" @ok="upConfirm">
      <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }" style="padding-top: 50px;">
        <a-form-item label="上级">
          <a-select show-search placeholder="请选择" option-filter-prop="label" :filter-option="filterOption"
            v-model:value="upId">
            <a-select-option v-for="user in options" :key="user.id" :value="user.id"
              :label="user.username + ' ' + user.phone" @click="handleChange(user)">
              {{ user.realname }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:visible="recommendShow" style=" width: 800px;" @ok="recommendShow = false">
      <div style="overflow: hidden;">
        <div style="text-align: center;margin-top: 20px;font-weight: 600;font-size:24px;">我的上级</div>
        <a-table :dataSource="upData" :columns="upList" :pagination="false">
          <template #bodyCell="{ column, text, record }">
            <template v-if="column.dataIndex === 'edit'">
              <div @click="editRecommend(record)">修改</div>
            </template>
          </template>
        </a-table>
      </div>
      <div style="overflow: hidden;">
        <div style="text-align: center;margin-top: 20px;font-weight: 600;font-size:24px;">我的下级</div> <a-table
          :dataSource="downData" :columns="downList" />
      </div>
    </a-modal>
    <a-modal v-model:visible="chongShow" @ok="chongOk">
      <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }" style="padding-top: 50px;">
        <a-form-item label="充值余额">
          <a-input type="number" v-model:value="amount" />
        </a-form-item>
        <a-form-item label="充值说明">

          <a-textarea v-model:value="type" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" name="shipMember-shipMember" setup>
import { ref, computed, unref, reactive, onMounted } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import UserDrawer from './modules/UserDrawer.vue';
import { useDrawer } from '/@/components/Drawer';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage'
import ShipMemberModal from './modules/ShipMemberModal.vue'
import { columns, searchFormSchema } from './ShipMember.data';
import {
  list, getImportUrl, getExportUrl, deleteUser, saveMerchantPoint, userUp, setShop, myRecommend, modifyTheSuperior, memberIncomeAdd
} from './ShipMember.api';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import { object } from 'vue-types';
onMounted(() => {
  getList()
})
//注册drawer
const [registerDrawer, { openDrawer }] = useDrawer();
//注册model
const [registerModal, { openModal }] = useModal();

//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '用户详细信息表',
    api: list,
    columns,
    canResize: false,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
    },
    actionColumn: {
      width: 120,
    },
  },
  exportConfig: {
    name: "用户详细信息表",
    url: getExportUrl,
  },
  importConfig: {
    url: getImportUrl
  },
})
const visible = ref<boolean>(false);
const recommendShow = ref<boolean>(false);
const editUp = ref<boolean>(false);
const upId = ref<boolean>();
const downId = ref<boolean>();
const chongShow = ref<boolean>();
const chongInfo = reactive({
  username: '',
  id: ''
});
const type = ref();

const chong = reactive({
  amount: '',
  remark: "",
  merchantId: ''

});
const amount = ref('')

const userId = ref('')
const level = ref('')
const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext
const options = ref()
// 选择上级
const handleChange = (data) => {
  upId.value = data.id;
};

const upConfirm = () => {

  modifyTheSuperior({
    memberId: downId.value,
    newMasterId: upId.value
  }).then(res => {
    editUp.value = false
  })
};


const getList = () => {
  let demo1 = []
  let demo2 = []
  list({
    userType: 2,
    type: 'other',
    pageSize: 99
  }).then((res) => {
    console.log(1)

    if (res) {
      demo1 = res.records
      list({
        type: 'other',
        userType: 1,
        pageSize: 99


      }).then((res) => {
        if (res) {
          console.log(2);

          demo2 = res.records
          options.value = [...demo1, ...demo2]
        }
      })
    }
  })

}
const filterOption = (input, option) => {
  const label = option.label.toLowerCase();

  return label.includes(input.toLowerCase());
};
const upData = reactive([])
const downData = reactive([])

const upList = reactive([
  {
    title: '用户账号',
    dataIndex: 'username',
    key: 'username',
    align: 'center'

  },
  {
    title: '姓名',
    dataIndex: 'realname',
    key: 'realname',
    align: 'center'

  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    align: 'center',

  },
  {
    title: '操作',
    dataIndex: 'edit',
    align: 'center',
    key: 'edit',
  },
])
const downList = reactive([
  {
    title: '用户账号',
    dataIndex: 'username',
    key: 'username',
    align: 'center'

  },
  {
    title: '姓名',
    dataIndex: 'realname',
    key: 'realname',
    align: 'center'

  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    align: 'center',

  }
])
/**
 * 新增事件
 */
function handleAdd() {
  openDrawer(true, {
    isUpdate: false,
    showFooter: true,
    tenantSaas: false,
  });

  //  openModal(true, {
  //    isUpdate: false,
  //    showFooter: true,
  //  });
}
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
    showFooter: true,
    tenantSaas: false,
  });
}
function give(record: Recordable) {
  chong.merchantId = record.id;
  visible.value = true;
}
const handleOk = () => {
  userUp({
    userId: userId.value,
    grade: level.value
  }).then(res => {
    visible.value = false;

    reload();

  })
};
/**
 * 详情
*/
function handleDetail(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
    showFooter: false,
    tenantSaas: false,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {

  await deleteUser({ id: record.id }, reload);
}
/**
 * 批量删除事件
 */
// async function batchHandleDelete() {
//   await batchDelete({ ids: selectedRowKeys.value }, reload);
// }
/**
 * 成功回调
 */
function handleSuccess({ isUpdate, values }) {
  reload();
}

function upLevel(record) {
  visible.value = true
  userId.value = record.id;
}
const setShopMethod = (record) => {
  let demo = {
    id: record.id,
    userType: '2'
  }
  setShop(demo).then(res => {
    reload();
  })
}
const chongOk = () => {
  let data = {
    memberName: chongInfo.realname,
    memberId: chongInfo.id,
    amount: amount.value,
    isLocked: 1,
    type: type.value

  }
  memberIncomeAdd(data).then(res => {

    chongShow.value = false;

  })
}
const recommend = (record) => {
  downId.value = record.id
  myRecommend({ memberId: record.id }).then(res => {
    recommendShow.value = true
    let firstRec = []
    let mySuperior = []
    res.firstRec.forEach(v => {
      firstRec.push(v.userInfo)
    })
    mySuperior.push(res.mySuperior)

    Object.assign(upData, mySuperior)
    Object.assign(downData, firstRec)

  })

}
const editRecommend = (record) => {
  editUp.value = true;
}
const yu = (record) => {
  Object.assign(chongInfo, record);
  chongShow.value = true;
}

/**
   * 操作栏
   */
function getTableAction(record) {
  return [
    {
      label: '余额充值',
      onClick: yu.bind(null, record),
    },
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    },

    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
    {
      label: '升级',
      onClick: upLevel.bind(null, record),
    },
    {
      label: '设置为商家',
      // onClick: setShopMethod.bind(null, record),
      popConfirm: {
        title: '是否确认',
        confirm: setShopMethod.bind(null, record),
        placement: 'topLeft',
      },
    },
    {
      label: '推荐关系',
      onClick: recommend.bind(null, record),
    },
  ]
}


/**
  * 下拉操作栏
  */
// function getDropDownAction(record) {
//   return [
//     {
//       label: '详情',
//       onClick: handleDetail.bind(null, record),
//     },
//   ]
// }
</script>
<style scoped></style>